package com.rtsapp.server.profiling;

import java.util.concurrent.locks.LockSupport;

/**
 * 周期性的表
 */
public  class PeriodClock {

    private volatile long currentMills = System.currentTimeMillis();
    private final long period;


    public PeriodClock(long period){
        this.period = period;

        final Thread updater = new Thread( new PeriodClockThread() , "PeriodClock" );
        updater.setDaemon( true );
        updater.start();

    }

    public static PeriodClock newSecondClock(){
        return new PeriodClock(  1000 * 1000 * 1000 );
    }

    /**
     * 获得当前时间
     * 线程安全
     * @return
     */
    public long getTimeMills(){
        return currentMills;
    }


    private void setCurrent(){
        currentMills = System.currentTimeMillis();
    }


    private class PeriodClockThread implements Runnable{

        @Override
        public void run() {
            while ( true ){
                setCurrent();
                LockSupport.parkNanos(period);
            }
        }
    }

}